<?php

class EwalletController extends UController
{
    /**
     * E钱包详情
     */
    public function actionDetail()
    {
        $data = array('success'=>1);
        $e    = User::model()->getEwalletInfo($this->userId);
        $info = MRedis::getEconfig();
        $data['interestToady']      = $e['interestToady'];//今日收益
        $data['eBalance']           = $e['eBalance'];//e钱包余额
        $data['eTotal']             = $e['eTotal'];//e钱包本金加待收利息
        $data['interestTotal']      = $e['interestTotal'];//历史总收益
        $data['receivableInterest'] = $e['receivableInterest'];//可提利息
        $data['name']               = $info->name;//e钱包名称
        $data['rate']               = $info->rate;//利率
        $data['min']                = $info->minAmount;//最低投资额
        $data['totalNum']           = intval(Yii::app()->cache_new->hget('totalSummary','total_demand_count'));//e钱包理财次数
        $data['tip']                = $info->desc;//会生钱
        $data['fee']                = $info->redeemRate;//fee
        $data['interestFrom']       = $info->interestFrom;// T+1
        $data['redeemTip']          = $info->redeemTimeTip;//最快0秒 一般1-2天
        $data['redeemFeeTip']       = $info->redeemFeeTip;//免手续费
        $data['redeemRule']         = $info->redeemRule;//不限金额，一天可转出一次
        $data['yearInterest']       = number_format(10000*$data['rate']/365/100*364,2,'.','');
        $info = User::model()->findById($this->userId);
        $data['payPassSet']        = $info->resetPayPass;
        $cap  = User::model()->getCapital($this->userId);
        $data['capitalAccountBalance'] = $cap['capitalAccountBalance'];
        $data['autoIn']            = Yii::app()->cache2->hget($this->userId.".Capital","demandAuto")?1:0;//是否自动转入
        $this->setResult($data);
    }
    /**
     * 第三方支付订单
     */
    public function actionAffirmredirect()
    {
        $data       = array('success'=>0,'msg'=>'');
        $payNeeded  = $this->_post('payneeded');
        $bank_id    = $this->_post('bank_id',null);
        $pay_method = $this->_post('pay_method');
        $banks      = Yii::app()->params['mobileBanks'];
        $usableIds  = array();
        foreach($banks as $b)
            $usableIds[] = $b['code'];

        if(!in_array($bank_id, $usableIds))
            $data['msg'] = '暂不支持该银行支付';
        elseif(!$payNeeded || $payNeeded<=0)
            $data['msg'] = '支付金额必须大于0';
        else
        {
            $order           = $this->saveOrder($bank_id,$pay_method);
            $data["tradeNo"] = $order->result->tradeNo;
            $data['success'] = 1;
        }
        $this->setResult($data);
    }

    /**
     * 保存订单
     * pay_method: 0：余额支付 3：连连支付,1：易生，2：盛富通
     * @return mixed|null
     */
    private function saveOrder($bank_id='',$pay_method = 0)
    {
    	$data = array(
			'success'  => 0,
			'msg' => '',
    	);
        $model       = User::model();
        $user        = $model->findById($this->userId);
        $password    = $this->_post('password');
        $cap         = $this->_post('cap',0);//余额支付金额
        $amount      = $this->_post('amount'); //投资金额
        $pay_amount  = $this->_post('payneeded',0);//第三方支付金额
        $order_from  = $this->_post('order_from');//订单来源 1:android 2:ios
        $card_number = $this->_post('card_no');//银行卡号
        $projectId   = Yii::app()->cache2->hget('demandInfo','projectId');
        if(!$password || !$model->checkPayPass($this->userId,$password))
        	$data['msg'] = '交易密码不正确';
        elseif(!$projectId)
            $data['msg'] = '草根钱包项目不存在';
        elseif($amount>Yii::app()->cache2->get($projectId.'.Investable'))
            $data['msg'] = '钱包项目已满额，去看看其他项目吧';
        elseif(!in_array($pay_method, array(0,3)))
        	$data['msg'] = '暂不支持该支付方式';
        elseif(!in_array($order_from, array(1,2)))
        	$data['msg'] = 'order_from参数不合法';
        elseif(SITEMODE !== 'DEVELOP' && $cap+$pay_amount != $amount)
        	$data['msg'] = '支付总额不等于投资金额';
        if($pay_method!=0 && $pay_amount==0)
        	$data['msg'] = '手机充值业务正在维护中';
        elseif(in_array($pay_method, array(3)))
        {
            $maxAmount = Helper::getMaxPayAmount($bank_id,$pay_method);
            if($pay_amount > $maxAmount*10000)
            	$data['msg'] = '该银行卡单笔最高可支付'.($maxAmount>=1?$maxAmount.'万':10000*$maxAmount).'元';
        }
        if($data['msg'])
        	$this->setResult($data);
        $bank_code = '';
        if($bank_id)
        {
            $banks = Yii::app()->params['mobileBanks'];
            foreach($banks as $b)
            {
                if($b['code'] == $bank_id)
                {
                    $bank_code = $b['alias'];
                    break;
                }
            }
        }
        $data = array(
            'user_id'            => $this->userId,
            'invest_amount'      => $amount,
            'method'             => ($pay_amount==0)?0:$pay_method,
            'bank_code'          => $bank_code,
            'used_capital'       => $cap,
            'pay_amount'         => $pay_amount,
            'order_from'         => $order_from,
            'card_no'            => $card_number,
        );
        $remote = HttpLib::post($this->javaApi['ewallet_create_order'],$data);
        Helper::positionRecord('e-order',$this->userId);
        if($remote->result && $remote->result->success && $remote->result->result->tradeNo)
            return $remote->result;
        else
            $this->setResult(array(
                'success' => 0,
                'msg'     => $remote->result->errorMsg,
            ));
    }
    /**
     * 直接交易页面（余额支付）
     */
    public function actionAffirmdo()
    {
        $data    = array('success'=>0);
        $order   = $this->saveOrder('',0);
        $tradeNo = $order->result->tradeNo;
        Yii::trace('e钱包 余额支付 订单号是'.$tradeNo);
        $result = HttpLib::post($this->javaApi['do_transaction'],array(
            'trade_no' => $tradeNo,
            'user_id'  => $this->userId,
        ));
        if($result && $result->success)
        {
            $remote = HttpLib::get($this->javaApi['pay_invest_over'],array(
                        'trade_no' => $tradeNo,
                        'user_id'  => $this->userId,
                        'token'    => $this->token,
            ));
            if($remote->result->success)
            {
                $data['success']      = 1;
                $data['paying']       = 0;
            }
            elseif($remote->result->code == 20528)
            {
                $data['success']      = 1;
                $data['paying']       = 1;//支付中
            }
            else
                $data['msg']     = $remote->result->errorMsg;
        }
        else
            $data['msg']     = $result->errorMsg;
        $this->setResult($data);
    }
    /**
     * 赎回展示
     * @return [type] [description]
     */
    public function actionRedeem()
    {
        $data                       = array('success'=>1);
        $e                          = User::model()->getEwalletInfo($this->userId);
        $data['eBalance']           = $e['eBalance'];//余额
        $data['receivableInterest'] = $e['receivableInterest'];//待收利息
        $info                       = User::model()->getE30DayInfo($this->userId);
        $data['inner']              = $info['inner'];
        $data['outer']              = $info['outer'];
        $einfo = MRedis::getEconfig();
        $data['fee']                = $einfo->redeemRate;//fee
        $data['freeDays']           = $einfo->redeemFreeDay;//免手续费天数
        $data['redeemed']           = 0;
        $data['redeemTip']          = '利息随同转出本金同时到达您草根账户';
        $num = $einfo->maxNumRedeem;
        if(Yii::app()->cache2->hget('demandRedeemTimes',$this->userId)>=$num)
        {
            $data['redeemed']    = 1;
            $data['redeemedTip'] = '今天您已转出过一次了，请明天再来';
        }
        $this->setResult($data);
    }
    /**
     * 赎回操作
     */
    public function actionRedeemDo()
    {
        $data     = array('success'=>0);
        $amount   = $this->_post('amount',0);
        $model    = User::model();
        $e        = $model->getEwalletInfo($this->userId);
        $password = $this->_post('password');
        $info = MRedis::getEconfig();
        $num  = $info->maxNumRedeem;
        if(Yii::app()->cache2->hget('demandRedeemTimes',$this->userId) >= $num)
            $data['msg'] = '今天您已转出过'.$num.'次了，请明天再来';
        elseif($amount<=0)
            $data['msg'] = '转出金额不对';
        elseif($amount>$e['eBalance'])
            $data['msg'] = '转出金额大于草根钱包余额';
        elseif(!$password || !$model->checkPayPass($this->userId,$password))
            $data['msg'] = '交易密码不正确';
        else
        {
            $remote = HttpLib::post($this->javaApi['ewallet_redeem'],array(
                'redeem_amount' => $amount,
                'user_id'       => $this->userId,
            ));
            if($remote->success)
            {
                Helper::positionRecord('e-redeem',$this->userId);
                $data['success']   = 1;
                $data['redeemTip'] = $info->redeemTimeTip;//最快0秒
            }
            else
                $data['msg'] = $remote->errorMsg;
        }
        $this->setResult($data);
    }
    /**
     * 转入转出列表
     */
    public function actionList()
    {
        $data = array('success'=>0);
        $params = array(
            'user_id'    => $this->userId,
            'page'       => $this->_post('page',1),
            'limit'      => $this->_post('limit',5),
            'query_type' => $this->_post('type'),//type(全部传1,转入传2，转出传3)
        );
        if(!in_array($params['query_type'], array(1,2,3)))
            $data['msg'] = '参数不合法';
        else
        {
            if($params['query_type']==1)
            {
                $e    = User::model()->getEwalletInfo($this->userId);
                $data['eTotal']             = $e['eTotal'];//e钱包本金加待收利息
                $data['eBalance']           = $e['eBalance'];//e钱包余额
                $data['receivableInterest'] = $e['receivableInterest'];
            }
            $remote = HttpLib::post($this->javaApi['wallet_list'],$params);
            if($remote->success)
            {
                $data['success'] = 1;
                $data['total']   = $remote->result->totalCount;
                $data['pageNum'] = $remote->result->pageNum;
                $data['list']    = array();
                if($remote->result->pageList)
                {
                    foreach($remote->result->pageList as $v)
                    {
                        $amount = strpos($v->operation, '转入') !== false?$v->amount:-$v->amount;
                        $data['list'][] = array(
                            'amount'    => number_format($amount,2,'.',''),
                            'operation' => $v->operation,
                            'time'      => date('Y-m-d H:i',strtotime($v->time)),
                            'progress'  => $v->progress?1:0,
                        );
                    }
                }
            }
            else
                $data['msg'] = $remote->errorMsg;
        }
        $this->setResult($data);

    }
    /**
     * 设置自动转入
     */
    public function actionSetAuto()
    {
        $data   = array('success'=>0);
        $params = array(
            'user_id' => $this->userId,
            'flag'    => $this->_post('autoIn'),  //1:自动转入 0：取消自动转入
        );
        $remote = HttpLib::post('demand/auto/setting.json',$params);
        if($remote->success)
        {
            Yii::app()->cache2->hset($this->userId.".Capital","demandAuto",$params['flag']);
            $data['success'] = 1;
        }
        else
            $data['msg'] = $remote->errorMsg;
        $this->setResult($data);
    }

    /**
     * 收益历史
     */
    public function actionInterestHistory()
    {
        $page  = $this->_post('page',1);
        $limit = $this->_post('limit',10);
        $list = User::model()->getInterestHistory($this->userId,$page,$limit);
        $e    = User::model()->getEwalletInfo($this->userId);
        $data = array(
            'success'            => 1,
            'totalCount'         => $list['total'],
            'pageNum'            => $list['pageNum'],
            'minInterest'        => $list['min'],
            'maxInterest'        => $list['max'],
            'receivableInterest' => $e['receivableInterest'],//待转出利息
            'receivedInterest'   => $e['receivedInterest'],//待转出利息
            'interestTotal'      => $e['interestTotal'],//待转出利息
            'list'               => array(),
        );
        if($list['list'])
        {
            foreach($list['list'] as $v)
            {
                $v = json_decode($v);
                $data['list'][] = array(
                    'interest' => Helper::formatNumber($v->interest,5,true),
                    'date'     => date('Y-m-d',$v->date/1000),
                );
            }
        }
        $this->setResult($data);
    }
}
